<template>
  <div class="panel">
    <PanelTitle title="库位列表"></PanelTitle>
    <div class="panel-body">

      
        
   
      <!--搜索框-->
      <!-- <el-form :inline="true" class="demo-form-inline">


        <el-form-item prop="image" label="上传图片">
          <el-upload
            v-model="imgfile"
            :action="''"
            list-type="picture-card"
            :http-request="upload"
            :limit="1"
            :on-exceed="limitError"
            :on-success="imgSuccess"
            :on-error="imgError"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      
        

    
      </el-form>
      <PanelTitle title="识别结果"></PanelTitle>
      <div class="panel-body">
      <textarea prop = "textRes" v-model="textRes" label="识别结果"
         style="width: 100% ; height: 100px">
        :data="clients.data"
        :text="textRes"
      ></textarea>
      </div> -->

      <PanelTitle title="粘贴上传图片"></PanelTitle>  
      <div>
        <div>
        <textarea placeholder="在这里粘贴图片" placeholderfont="1px" v-model="picfile"
          border
          align="center"
          style="width: 100% ; height: 30px; "  @paste="handlePaste">
         
        </textarea>
        
      </div>
      <PanelTitle title="图片回显" style= "margin-top: 5%;"></PanelTitle>  
        <div style="border: 2px; color: #999; " v-for="(image, index) in images" :key="index">
              <img :src="image" alt="粘贴的图片" />
        </div>
      </div>


      <PanelTitle title="粘贴上传图片识别结果" style= "margin-top: 10%;"></PanelTitle>  
      <div>
          <textarea v-model="pasteContent"  style="width: 100% ; height: 100px"></textarea>
      </div>
      <!-- <el-table
        v-loading="clients.loading"
        size="mini"
        :data="clients.data"
        border
        style="width: 100%"
        highlight-current-row
      > -->
      <!--     <el-table-column
          prop="rank"
          label="排名"
          align="center"
          min-width="5%"
        >
        <template slot-scope="scope">
                {{scope.$index+1+(clients.current-1)*clients.size}} 
              </template>
          </el-table-column> -->
        <!-- <el-table-column
          prop="id"
          label="舆论ID"
          width="80px"
          align="center"
          show-overflow-tooltip
        >
        </el-table-column> -->
        <!-- <el-table-column
          prop="data"
          label="识别结果"
          align="center"
          min-width="20%"
        >
       </el-table-column>
        
  
      </el-table> -->
      <!-- <div class="block" style="margin-top: 2%;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="clients.pageNo"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="clients.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="clients.total">
        </el-pagination>
      </div> -->
    </div>
  </div>
</template>
<script>
  import PanelTitle from '@/components/PanelTitle.vue'
  import {ImageRecognitionService} from '@/utils/api'
  import moment from 'moment'

  export default {
    data() {
      return {
        clients: {
          total: 0,
          pageSize: 20,
          pageNo: 1,
          topicList: []
        },
        imgfile:null,
        pasteContent: '',
        images: [],
        picfile:null,
        textRes: null,
        searchCrawlDate: [],
       
        sentimentOptions: [{
          value: 1,
          label: '正面'
        }, {
          value: 0,
          label: '中立'
        }, {
          value: -1,
          label: '负面'
        }],
      }
    },
    components: {
      PanelTitle
    },
   
    created() {
      // this.getTopicPageData()
    },
    methods: {
     // 图片上传前验证
    beforeAvatarUpload (file) {
       const isLt2M = file.size / 1024 / 1024 < 2
       if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
       }
       return isLt2M
      },
      // 上传图片到OSS 同时派发一个事件给父组件监听
      upload (item) {
        let params = new FormData()
        params.append('file', item.file)
        console.log(item)
        params.append('fileName', item.file.name)
        params.append('fileType', item.file.type)
        params.append('fileSize', item.file.size)
        params.append('fileLastModified', item.file.lastModified)
        params.append('fileLastModifiedDate', item.file.lastModifiedDate)

        ImageRecognitionService.getImageRecognitionResult(params).then(res => {
          console.log(res)
          if(res.data.code==200){
            this.clients = res.data
            this.textRes = this.clients.data
            // console.log(this.clients.data)
          }else{
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
        
      //  getAliOSSCreds().then(res => { // 向后台发请求 拉取OSS相关配置
      //   let creds = res.body.data
      //   let client = new OSS.Wrapper({
      //    region: 'oss-cn-beijing', // 服务器集群地区
      //    accessKeyId: creds.accessKeyId, // OSS帐号
      //    accessKeySecret: creds.accessKeySecret, // OSS 密码
      //    stsToken: creds.securityToken, // 签名token
      //    bucket: 'imgXXXX' // 阿里云上存储的 Bucket
      //   })
      //   let key = 'resource/' + localStorage.userId + '/images/' + createId() + '.jpg' // 存储路径，并且给图片改成唯一名字
      //   return client.put(key, item.file) // OSS上传
      //  }).then(res => {
      //   console.log(res.url)
      //   this.$emit('on-success', res.url) // 返回图片的存储路径
      //  }).catch(err => {
      //   console.log(err)
      //  })
    },
       // 上传成功
    imgSuccess(res, file) {
      this.imageUrl = res.data;
      this.form.image = this.imageUrl;
      console.log(res.data);
    },
    // 上传失败
    imgError(res) {
      this.$message({
        type: "error",
        message: "附件上传失败",
      });
    },
    // 上传数量超限
    limitError() {
      this.$message({
        type: "error",
        message: "图片仅可上传一张",
      });
    },
      //获取数据  
      getTopicPageData() {
        const searchDTO = {
          //查询参数
          size: this.clients.pageSize,
          current: this.clients.pageNo,
          skuCode: this.skuCode,
          oldSkuCode: this.oldSkuCode,
          whCode: this.whCode,
          startDate: this.searchCrawlDate!=null ? this.searchCrawlDate[0] : null,
          endDate: this.searchCrawlDate!=null ? this.searchCrawlDate[1] : null,
        }
        // InventoryServcie.pageSearchWmsInvstorage(searchDTO).then(res => {
        //   console.log(res)
        //   if(res.data.code==200){
        //     this.clients = res.data.data
        //     // console.log(this.clients)
        //   }else{
        //     this.$message.error(res.data.msg)
        //   }
        // }).catch(err => {
        //   this.$message.error(err)
        // })
      },
      handleSizeChange(val) {
        this.clients.pageSize = val
        this.getTopicPageData()
      },
      handleCurrentChange(val) {
        this.clients.pageNo = val
        this.getTopicPageData()
      },
      dateFormat(dateTime) {
        if (dateTime == undefined) {
          return "";
        }
        return moment(Number(dateTime)).format("YYYY-MM-DD HH:mm:ss");
      },
      handlePaste(event) {
      this.images = [];
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];
          console.log(item.type);
          if (item.type === 'text/plain') {
            this.pasteContent = item.getAsString();
            console.log(this.pasteContent);
          }
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            this.uploadImage(file);
            const url = URL.createObjectURL(file);
            this.images.push(url);
          }
        }
      }
    },
    uploadImage(file) {
      // 创建FormData
      let params = new FormData()
        params.append('file', file)
        params.append('fileName', file.name)
        params.append('fileType', file.type)
        params.append('fileSize', file.size)
        params.append('fileLastModified', file.lastModified)
        params.append('fileLastModifiedDate', file.lastModifiedDate)

        ImageRecognitionService.getImageRecognitionResult(params).then(res => {
          console.log(res)
          if(res.data.code==200){
            this.clients = res.data
            this.pasteContent = this.clients.data
            // console.log(this.clients.data)
          }else{
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          this.$message.error(err)
        })
      // // 这里使用axios发送图片，你可以替换为你的上传逻辑
      // axios.post('/img/recognition', formData, {
      //   headers: {
      //     'Content-Type': 'multipart/form-data'
      //   }
      // })
      // .then(response => {
      //   console.log('图片上传成功', response);
      // })
      // .catch(error => {
      //   console.error('图片上传失败', error);
      // });
      },
      pasteImg(blob) {
            let self = this;
            // blob 就是从剪切板获得的文件 可以进行上传或其他操作
            var imgs = new Image();
            var reader = new FileReader();
            reader.onload = (function (aImg) {
                return function (e) {
                    self.pasteUrl = e.target.result;
                };
            })(imgs);
            reader.readAsDataURL(blob);
        },


      add(a,b,c){
        return a+b+c
      },
      cleanSearch() {
        this.imgfile = null
       
      },
      jumpToDetail(id) {
        this.$router.push({
          name: 'consensusDetail',
          query: {id: id}
        })
        this.$store.commit('selectMenu', {
          title: "话题分析",
          path: "/consensus/detail",
          name: 'consensusDetail',
          icon: "el-icon-date",
        })
      },
      
    },
  }
</script>

<style>
  .line-limit-length {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
